<!--
 * @Author: Bobby
 * @Date: 2021-12-30 10:01:42
 * @LastEditTime: 2022-03-24 12:01:13
 * @LastEditors: Bobby
 * @Description:
 * @FilePath: \wms-v2\src\ve\elements\basic\uiTable\uiTable.vue
 * CIMC-V2
-->

<template>
  <div :id="'uiTable-body-' + info._id" ref="uiTable-body" class="ui-tabel relative" :class="[hasMini ? 'table-mini' : '']">
    <div class="ui-flexbox min-h-[22px]"></div>
    <vxe-grid
      :ref="info._id"
      v-ui-ref="vSetRef"
      v-bind="gridOptions"
      :keyboard-config="tableKeyboardConfig"
      :mouse-config="{ selected: true }"
      :row-style="rowStyle"
      :scroll-x="scrollXConfig"
      :scroll-y="{ gt: 50 }"
      @cell-dblclick="cellClickEvent"
      @checkbox-change="checkboxChange"
      @keydown="handlerEnter"
      @page-change="pageChange"
      @sort-change="sortChange"
    >
      <!-- 工具栏 -->
      <template #toolbar_tools>
        <vxe-button class="refresh-btn" size="mini" @click="onRefresh">
          <vui-icon :class="{ roll: hasClickRefreshLoading }" icon="refresh-line" />
        </vxe-button>
      </template>
      <!-- <template #num_default="{ row, rowIndex }">
        <el-switch v-model="row.num" @change="tableSwitch(row, rowIndex)" />
      </template> -->
      <!-- 多选头 -->
      <template #checkbox_header="{ checked, indeterminate }">
        <div class="flex cursor-pointer">
          <span class="custom-checkbox" @click.stop="checkboxSelectAll">
            <template v-if="indeterminate">
              <i class="ri-checkbox-indeterminate-line text-blue-500"></i>
            </template>
            <template v-else-if="checked">
              <i class="ri-checkbox-fill text-blue-500"></i>
            </template>
            <template v-else>
              <i class="ri-checkbox-blank-line text-gray-300"></i>
            </template>
          </span>
          <!-- <span @click="checkboxSelectAll">{{ column.title }}</span> -->
          <span>/</span>
          <span @click="checkboxReverseSelection">{{ translateTitle(`Ve.elements.table.反选`) }}</span>
        </div>
      </template>

      <!-- 空数据 -->
      <template #empty>
        <el-empty :description="translateTitle('Ve.elements.table.暂无数据')" />
      </template>
    </vxe-grid>
  </div>
</template>
<script>
  import request from '@/utils/request'
  import isEmpty from 'lodash/isEmpty'
  import trim from 'lodash/trim'
  import isArray from 'lodash/isArray'

  import Sortable from 'sortablejs'
  import { GFCD } from '@/utils/utils'
  import { defineComponent } from 'vue'
  import { UiMixin, RefsInjectMixin } from '@ve/mixin'
  import { actionsTask } from '@ve/eventTask/index'
  import cloneDeep from 'lodash/cloneDeep'
  import { processingConstant } from '@ve/utils/utils'
  import isFunction from 'lodash/isFunction'
  import { domHeight } from '@ve/utils/domHeight'
  import { translateTitle } from '@/utils/i18n'

  const meanNum = (list, field) => {
    let count = 0
    list.forEach((item) => {
      count += Number(item[field])
    })
    return count <= 0 || list.length <= 0 ? 0 : (count / list.length).toFixed(2)
  }
  const sumNum = (list, field) => {
    let count = 0
    list.forEach((item) => {
      count += Number(item[field])
    })
    return count.toFixed(2)
  }
  export default defineComponent({
    name: 'UiSelectNewTable',
    mixins: [UiMixin, RefsInjectMixin],
    props: {
      formDataModel: {
        type: null,
        default: '',
      },
    },
    emits: ['outSelected', 'tableEnterEvent'],
    data() {
      return {
        dataSourceChangeIndex: 0,
        columnSortable: null,
        pageSize: 1,
        tabelHeight: 300,
        list: [],
        loading: false,
        //click记录
        clickRowId: '', //点击行id 单击双击
        hasClickRefreshLoading: false,
        cacheFormData: {}, //缓存formdata
        hasCheckboxSelectAll: false, //是否全选
        selectRow: {}, //选中数据行
        //可编辑slots数据
        editSlots: [],
        hasOpenEdit: false,
        // editActivedVisible: false,
        //操作按钮
        //排序状态
        sortType: {},
        //批次属性表头
        batchAttributeColumns: [],
        dataSourceFormData: {}, // 数据源绑定获取的数据（不作为参数使用时）
        hasMini: false,
        //缓存编辑模式下的数据
        cacheEditRows: {},
        editFormItem: '', // 当前触发改变的表单项
        scrollXConfig: {
          gt: 10,
          enabled: false,
        },
        tableKeyboardConfig: {
          isArrow: true,
          isChecked: true,
        },
      }
    },
    computed: {
      currentPage() {
        return this.info.data.formData['#LIMIT#']
      },
      getCount() {
        return this.info.data.requestData.count
      },
      getData() {
        return this.info.data.requestData.data
      },
      gridOptions() {
        let gridOptionsData = {
          rowConfig: {
            useKey: true,
            isHover: true,
            isCurrent: true,
          },
          columnConfig: {
            useKey: true,
            resizable: true,
          },
          showHeaderOverflow: true,
          keepSource: true,
          columnKey: true,
          stripe: true,
          loading: this.loading,
          resizable: true,
          autoResize: true,
          border: true,
          showOverflow: true,
          height: this.tabelHeight, //'auto',
          radioConfig: { highlight: true },
          checkboxConfig: { highlight: true },
          pagerConfig: {
            size: 'mini',
            pageSizes: this.info.extension.pageSizes.value.map((v) => Number(v)),
            pageSize: this.pageSize,
            total: this.getCount || 0,
            currentPage: this.currentPage,
          },
          // data: this.list || [],
          columns: this.getTableColumns,
          toolbarConfig: {
            slots: {
              tools: 'toolbar_tools',
            },
            className: 'vui-toolbar-box',
            custom: false,
          },
        }
        //底部合计
        if (this.info.extension.footerMethodConfig) {
          gridOptionsData.showFooter = this.info.extension.footerMethodConfig.value.open
          gridOptionsData.footerMethod = ({ columns, data }) => {
            let arr = []
            this.info.extension.footerMethodConfig.value.data.forEach((row) => {
              arr.push(
                columns.map((column, columnIndex) => {
                  if (columnIndex === 0) {
                    return this.info.extension.footerMethodConfig.value.options.find((el) => el.value == row.value).label
                  }
                  if (row.key.includes(column.property)) {
                    return row.value == '1' ? sumNum(data, column.property) : meanNum(data, column.property)
                  }
                  return ''
                })
              )
            })
            return arr
          }
        }
        if (this.info.extension.menuConfig) {
          let _menuConfig = this.info.extension.menuConfig.value
          _menuConfig.forEach((v) => {
            if (v.extension && v.extension.icon) {
              v.prefixIcon = `ri-${v.extension.icon.value}`
            }
          })
          gridOptionsData.menuConfig = {
            className: 'table-menus',
            body: {
              options: [_menuConfig || []],
            },
          }
        }
        return gridOptionsData
      },
      getPageSize() {
        return Number(this.info.extension.pageSize.value)
      },
      getInfo() {
        return this.info
      },
      getExtension() {
        return this.info.extension
      },
      //是否是单选或者多选
      hasCheckboxOrRadio() {
        let _type = ''
        this.getExtension.tableColumns.value.forEach((v) => {
          if (v._type == 'checkbox') {
            _type = 'checkbox'
          }
          if (v._type == 'radio') {
            _type = 'radio'
          }
        })
        return _type
      },
      getTableColumns() {
        //操作按钮
        let operateMenu = []
        if (this.info.extension.operateMenuConfig && this.info.extension.operateMenuConfig.value.length > 0) {
          let _width = 0
          this.info.extension.operateMenuConfig.value.forEach((v) => {
            if (v.extension.circle.value) {
              _width += 40
            } else {
              _width += 80
            }
          })

          operateMenu = [
            {
              _type: 'operate',
              showOverflow: true,
              title: '操作',
              width: _width,
              fixed: this.info.extension.operateMenuConfig.setting.fixed,
              slots: {
                // default: 'operate',
                default: ({ row, column }) => {
                  return [
                    <div class="flex justify-center">
                      {this.getOperateMenu.map((v) => {
                        if (!this.handleStatusConfig(row, v)) {
                          return (
                            <el-button
                              onClick={() => this.operateClick(v, row, column)}
                              circle={v.extension.circle.value}
                              plain={v.extension.plain.value}
                              round={v.extension.round.value}
                              type={v.extension.type.value}
                            >
                              {() => {
                                if (v.extension.icon.value) {
                                  return <vui-icon icon={v.extension.icon.value} />
                                }
                                if (!v.extension.circle.value) {
                                  return v.name
                                }
                              }}
                            </el-button>
                          )
                        } else {
                          return ''
                        }
                      })}
                    </div>,
                  ]
                },
              },
            },
          ]
        }
        let _tableColumns = [...cloneDeep(this.info.extension.tableColumns.value), ...operateMenu, ...this.batchAttributeColumns]

        // console.log('_tableColumns1', this.info.extension.operateMenuConfig, this.info.extension.operateMenuConfig.value.length > 0)
        //

        _tableColumns.forEach((v) => {
          v.width = `${v.width}px`
          v['minWidth'] = '70px'
          if (v._type === 'checkbox') {
            v['width'] = '56px'
            v.slots = {
              header: 'checkbox_header',
            }
          }

          if (v._type === 'seq') {
            v['width'] = '50px'
          }

          v['showHeaderOverflow'] = true
          v['searchConfig'] = v['searchConfig'] || {}
          //是否开启编辑 添加配置文件
          if (v.openEdit && this.hasOpenEdit) {
            v.editRender = {}
            if (v.slots) {
              v.slots['edit'] = v.field
            } else {
              v.slots = {
                edit: v.field,
              }
            }

            // this.editSlots.push(v.field)
            this.editSlots.push({
              field: v.field,
              formItemType: v.formModuleType || {},
            })
          } else {
            if (v.slots) {
              delete v.slots.edit
            }
          }

          //做进度条转换

          if (v._type === 'progress') {
            v.slots = {
              default: ({ row, column }) => {
                return [
                  <a title={row[column.property]}>
                    <el-progress percentage={row[column.property]} show-text={false} />
                  </a>,
                ]
              },
            }
          }
        })
        console.log('_tableColumns', _tableColumns)
        // if (this.development) {
        //   return _tableColumns
        // } else {
        //   if (this.getInfo.type.indexOf('uiSelectLayerNew') > -1) {
        //     return _tableColumns
        //   } else {
        //     return _tableColumns.filter(
        //       (el) => el.isChecked || el.isChecked === undefined || el._type == 'seq' || el._type == 'checkbox' || el._type == 'radio'
        //     )
        //   }
        //   // return _tableColumns
        //   //筛选下根据权限来渲染表头；根据表头字段isChecked为true或者为undefined(提示：因初始设置表头时没有设置这个参数，初始需要全部显示)
        // }
        return _tableColumns
      },
      getOperateMenu() {
        return this.info.extension.operateMenuConfig.value
      },
      getRowStatusConfig() {
        return this.info.extension.rowStatusConfig.value
      },
      getEditDefault() {
        return this.info.extension.clickEdit.value.editDefault
      },
    },
    watch: {
      getData: {
        immediate: true,
        handler: function (newval) {
          this.list = newval
          this.tableLoadData(newval)
        },
      },
    },
    created() {
      this.$sub(`SplitpaneResized_${this.previewPageId()}`, () => {
        this.getHeight()

        setTimeout(() => {
          this.getTableWidthProportion()
          // console.log('表格宽度变化', this.getTableRef().$el, this.getTableRef().$el.clientWidth)
        }, 200)
      })
    },
    mounted() {
      this.columnDrop()
      // 初始化赋值
      this.setFormData(1, this.getPageSize)
      this.cacheFormData = cloneDeep(this.getInfo.data.formData)
      this.hasOpenEdit = this.getInfo.extension.clickEdit ? this.getInfo.extension.clickEdit.value.open : false
      console.log('this.getTableColumns', this.getTableColumns)
      // this.tableLoadColumn(this.getTableColumns)

      this.$nextTick(() => {
        setTimeout(() => {
          this.getHeight()
        }, 100)
      })

      this.batchAttributeInit()
    },
    methods: {
      translateTitle,
      // 点击行选择 data
      cellClickEvent(data) {
        if (data.column && data.column.title == '操作') {
          console.log('点击操作区域不执行单行事件')
          return
        }

        // if (this.hasCheckboxOrRadio !== 'checkbox') {
        this.setRadioCheckboxRow(data, true)
        // }
      },
      // 点击了回车
      handlerEnter({ $event }) {
        if ($event && $event.key === 'Enter') {
          // 触发确认操作
          if (document.activeElement.className.indexOf('vfm__container') > -1) {
            this.$emit('tableEnterEvent')
          }
        }
      },
      addressClickEvent(row) {
        console.log('row', row)
      },
      getTableWidthProportion() {
        if (this.getTableRef() && this.getTableRef().$el) {
          let _tableWidth = this.getTableRef().$el.clientWidth
          let _winWidth = document.body.clientWidth
          // console.log('表格宽度变化', this.getTableRef().$el, _tableWidth, _winWidth, parseFloat((_tableWidth / _winWidth) * 100))
          let _proportion = parseFloat((_tableWidth / _winWidth) * 100)
          this.hasMini = _proportion <= 30 ? true : false
        }
      },
      handleStatusConfig(row, config) {
        let _status = false
        let expressionArr = []
        if (config.extension && config.extension.statusConfig && config.extension.statusConfig.value.length > 0) {
          let _statusConfig = config.extension.statusConfig.value
          // console.log('bbfpl 2', config)
          _statusConfig.forEach((item, index) => {
            let _val = processingConstant(this, item.value)
            if (item.conditions == '1') {
              if (row[item.key] == _val && item.execution == 'hide') {
                expressionArr.push(true)
              } else {
                expressionArr.push(false)
              }
            }
            if (item.conditions == '2') {
              if (row[item.key] != _val && item.execution == 'hide') {
                expressionArr.push(true)
              } else {
                expressionArr.push(false)
              }
            }
            if (index + 1 < _statusConfig.length) {
              expressionArr.push(item.operator || 'or')
            }

            // if (item.conditions == '1') {
            //   if (row[item.key] == _val && item.execution == 'hide') {
            //     _status = true
            //   }
            // }
            // if (item.conditions == '2') {
            //   if (row[item.key] != _val && item.execution == 'hide') {
            //     _status = true
            //   }
            // }
          })
        }
        if (expressionArr.length <= 0) {
          return false
        }

        let expression = ''
        expressionArr.forEach((v) => {
          let _v = v
          if (v == 'or') {
            _v = '||'
          }
          if (v == 'and') {
            _v = '&&'
          }
          expression = `${expression} ${_v}`
        })

        try {
          _status = new Function('return ' + expression)()
        } catch (error) {
          console.log('表格计算出错 -- ', error)
        }
        // console.log('bbfpl expressionArr1', config.name, expressionArr, expression, _status)
        return _status
      },
      tableLoadColumn(columns) {
        if (isEmpty(columns)) {
          columns = []
        }
        this.getTableRef() && this.getTableRef().reloadColumn(columns)
      },
      tableLoadData(data) {
        if (isEmpty(data)) {
          data = []
          // return
        }
        this.getTableRef() && this.getTableRef().loadData(data)
      },
      getTableRef() {
        return this.$refs[this.getInfo._id]
      },

      getHeight() {
        let _domHeight = domHeight(this)
        if (_domHeight > 0) {
          this.tabelHeight = _domHeight
          this.tabelHeight = this.getInfo.height || this.tabelHeight
        }
      },
      dataSourceChange(newval) {
        if (this.getInfo.dataSourceBind.hasParam.value) {
          let _mergeData = {}
          // 根据 getDataKey 筛选需要的数据
          if (!trim(this.dataSource.getDataKey)) {
            // 如果没有 getDataKey 则返回全量数据
            _mergeData = newval
          } else {
            const keyList = this.info.dataSourceBind.getDataKey?.value.split(',')
            isArray(keyList) &&
              keyList.forEach((item) => {
                item = trim(item)
                if (newval[item] !== undefined) {
                  // 如果传过来的对象里面没有要取得值 则丢弃
                  _mergeData[item] = newval[item]
                }
              })
          }
          this.getInfo.data.formData = {
            ...this.getInfo.data.formData,
            ..._mergeData,
          }
          //数据源变化后重新执行
          if (this.dataSourceChangeIndex != 0) {
            this.onLoad()
          }
        } else {
          this.list = newval.data
          this.tableLoadData(newval.data)
          // 缓存数据源绑定的值，以供自定义参数的变量获取使用
          let dataSourceFormData = {}
          const keyList = this.info.dataSourceBind.getDataKey?.value.split(',')
          isArray(keyList) &&
            keyList.forEach((item) => {
              item = trim(item)
              if (newval[item] !== undefined) {
                // 如果传过来的对象里面没有要取得值 则丢弃
                dataSourceFormData[item] = newval[item]
              }
            })
          this.dataSourceFormData = dataSourceFormData
        }
        this.dataSourceChangeIndex++
      },
      setFormData(currentPage, pageSize) {
        this.getInfo.data.formData['#LIMIT#'] = currentPage
        this.getInfo.data.formData['#PAGE_SIZE#'] = pageSize
        this.pageSize = pageSize
      },
      //
      rowStyle({ row }) {
        if (this.getRowStatusConfig && this.getRowStatusConfig.length > 0) {
          let color = {}
          this.getRowStatusConfig.forEach((v) => {
            if (row[v.key] && row[v.key] === v.value) {
              color = {
                backgroundColor: v.color,
                color: v.textColor == undefined ? '#000000' : v.textColor,
              }
            }
          })
          if (!isEmpty(color)) {
            return color
          }
        }
      },
      //表格选中变化统一方法
      onTableSelectChang() {
        this.runEventTask('onTableSelectChang', {
          tableId: this.info._id,
          data: this.getCheckboxOrRadioVals(),
        })
      },
      //多选触发
      checkboxChange(data) {
        this.onTableSelectChang()

        this.clickRowId = data.checked ? data.rowid : ''
        this.hasCheckboxSelectAll = this.getTableRef().isAllCheckboxChecked()
        //特定时间触发
        this.emitEvents()
      },
      // page修改
      pageChange(e) {
        let { currentPage, pageSize } = e
        if (this.pageSize != pageSize) {
          currentPage = 1
        }
        //页面修改 初始化到1页
        this.setFormData(currentPage, pageSize)
        // 做数组类型值的拼接
        const params = {}
        for (let key in this.getInfo.data.formData) {
          params[key] = isArray(this.getInfo.data.formData[key]) ? this.getInfo.data.formData[key].join() : this.getInfo.data.formData[key]
        }
        //请求
        this.request(
          {
            api: this.getInfo.extension.api.value,
            data: params,
            method: this.getInfo.extension.method.value,
          },
          function () {
            //没有需要选中的数据不执行
            if (!this.selectRow.row) {
              return
            }
            //触发选中
            this.setCheckboxRow(this.selectRow.row, this.selectRow.checked, this.selectRow.init)
          }
        )
      },
      //排序修改
      sortChange(data) {
        this.sortType[data.property] = data.order
      },
      // 统一请求
      request(options = {}, callback) {
        if (isEmpty(options.api) || isEmpty(options.method)) {
          this.$baseMessage('请填写表格Api 或者 Method')
          return
        }
        this.loading = true
        let getDataKey = this.getExtension.getDataKey.value
        //使用自定义参数
        console.log('请求数据 ----- 表格 ------  ', this.$getRequestData())
        let _data = options.data
        if (this.getInfo.type.indexOf('uiSelectLayerNew') === -1) {
          // 如果不是 选择新 组件触发的 则进行数据处理
          _data = { ...options.data, ...this.$getRequestData() }
        }
        //发起请求
        return request({
          url: GFCD('dams', 'domain') + options.api,
          method: 'post',
          data: {
            data: JSON.stringify(_data),
            method: options.method,
          },
        }).then((res) => {
          this.loading = false
          //解密
          // console.log(decryptd(res))
          this.getInfo.data.requestData = isEmpty(getDataKey) ? res.data : res.data[getDataKey]
          //添加回调
          callback && callback.call(this)
          // 默认选中第一个单元格
          setTimeout(() => {
            if (this.getInfo.data.requestData.data.length) {
              const tableColumn = this.getTableRef().getTableColumn().collectColumn
              const fullData = this.getTableRef().getTableData().fullData
              this.getTableRef().setSelectCell(fullData[0], tableColumn[0])
              if (!this.formDataModel) {
                // 如果formData没有值 则默认触发第一条数据的选中状态
                if (tableColumn[0] && tableColumn[0].type === 'checkbox') {
                  // 如果是多选 则调用多选的默认选中方法
                  this.getTableRef().setCheckboxRow(fullData[0], true)
                } else if (tableColumn[0] && tableColumn[0].type === 'radio') {
                  // 如果是单选 则调用单选的默认选中方法
                  this.getTableRef().setRadioRow(fullData[0])
                }
              }
            }
          })

          // setTimeout(() => {
          //   console.log(this.getTableRef().getSelectedCell())
          // }, 3000)
        })
      },
      setRadioCheckboxRow(data, isDbclick) {
        if (this.hasCheckboxOrRadio == 'radio') {
          this.getTableRef().setRadioRow(data.row)
          this.emitEvents([data.row], isDbclick)
        }
        if (this.hasCheckboxOrRadio == 'checkbox') {
          //双击先清空选择 再打勾
          // this.getTableRef().clearCheckboxRow()

          this.getTableRef().setCheckboxRow(data.row, true)
          this.emitEvents(null, isDbclick)
        }
      },
      getCheckboxOrRadioVals() {
        let _value = []
        if (this.hasCheckboxOrRadio == 'checkbox') {
          _value = this.getTableRef().getCheckboxRecords()
        } else {
          let v = this.getTableRef().getRadioRecord()
          _value = [v]
        }
        //特定组件触发
        this.emitEvents(_value)
        return _value
      },
      //表头拖动
      columnDrop() {
        this.$nextTick(() => {
          const $table = this.$refs[this.info._id]
          this.sortable2 = Sortable.create($table.$el.querySelector('.body--wrapper>.vxe-table--header .vxe-header--row'), {
            handle: '.vxe-header--column:not(.col--fixed)',
            onEnd: ({ item, newIndex, oldIndex }) => {
              const { fullColumn, tableColumn } = $table.getTableColumn()
              const targetThElem = item // 要移动的列（真实DOM）
              const wrapperElem = targetThElem.parentNode // 所有的列（真实DOM）
              const newColumn = fullColumn[newIndex] // 目标位置现有的列（虚拟DOM）
              if (newColumn.fixed) {
                // 错误的移动
                if (newIndex > oldIndex) {
                  wrapperElem.insertBefore(targetThElem, wrapperElem.children[oldIndex])
                } else {
                  wrapperElem.insertBefore(wrapperElem.children[oldIndex], targetThElem)
                }
                return this.$baseMessage('固定列不允许拖动！')
              }
              // 转换真实索引
              const oldColumnIndex = $table.getColumnIndex(tableColumn[oldIndex])
              const newColumnIndex = $table.getColumnIndex(tableColumn[newIndex])
              // 移动到目标列
              const currRow = fullColumn.splice(oldColumnIndex, 1)[0]
              fullColumn.splice(newColumnIndex, 0, currRow)
              $table.loadColumn(fullColumn)
            },
          })
        })
      },
      onRefresh(callback) {
        this.hasClickRefreshLoading = true
        try {
          this.$refreshTable().then(() => {
            if (isFunction(callback)) callback(this)
            this.hasClickRefreshLoading = false
          })
        } catch {
          ;() => {}
        }
      },
      //全选
      checkboxSelectAll() {
        this.onTableSelectChang()
        if (this.hasCheckboxSelectAll) {
          this.getTableRef().clearCheckboxRow(true)
        } else {
          this.getTableRef().setAllCheckboxRow(true)
        }
        this.hasCheckboxSelectAll = !this.hasCheckboxSelectAll
        //特定组件触发
        this.emitEvents()
      },
      //反选
      checkboxReverseSelection() {
        this.onTableSelectChang()
        const _table = this.getTableRef()
        //先获取当前选择
        const selectRecords = cloneDeep(_table.getCheckboxRecords())
        const allData = cloneDeep(_table.getData())
        console.log('allData', allData)

        let selectRecordsIds = []
        selectRecords.forEach((v) => {
          selectRecordsIds.push(v._X_ID)
        })
        let allDataIds = []
        allData.forEach((v) => {
          allDataIds.push(v._X_ID)
        })

        let arr = selectRecords.concat(allData)
        let result = arr.filter(function (v) {
          return selectRecordsIds.indexOf(v._X_ID) === -1 || allDataIds.indexOf(v._X_ID) === -1
        })
        //先清空当前选择 反选剩余的
        _table.clearCheckboxRow()
        _table.setCheckboxRow(result, true)
        //反射数据
        this.emitEvents(result)
      },
      //选中行
      setCheckboxRow(row, checked, init) {
        this.selectRow = {
          row: row,
          checked: checked,
          init: init,
        }
        //初始化执行
        if (init) {
          const getData = this.getData,
            result = []
          if (!getData) return
          for (let i = 0; i < row.length; i++) {
            for (let key in row[i]) {
              result.push(
                ...getData.filter((item) => {
                  return item[key] === row[i][key]
                })
              )
            }
          }
          row = result
        }
        //判断是单选还是复选
        if (this.hasCheckboxOrRadio === 'checkbox') {
          this.getTableRef().setCheckboxRow(row, checked)
        } else {
          this.getTableRef().setRadioRow(row[0])
        }
      },
      editActivedEvent({ row }) {
        this.cacheEditRows[row._X_ROW_KEY] = cloneDeep(row)

        if (isArray(this.getEditDefault)) {
          this.getEditDefault.forEach((v) => {
            row[v.key] = v.value //假设是默认值
          })
        }

        // this.editActivedVisible = true
      },
      async editClosedEvent({ column, row }) {
        let oldRow = this.cacheEditRows[row._X_ROW_KEY]
        const $table = this.getTableRef()
        const errMap = await $table.fullValidate()
        //判断默认值是否被修改
        const updateRecords = $table.getUpdateRecords()
        if (updateRecords) {
          if (isArray(this.getEditDefault)) {
            this.getEditDefault.forEach((v) => {
              if (row[v.key] == v.value) {
                //说明没修改过默认值 恢复原始值
                row[v.key] = oldRow[v.key]
              }
            })
          }
        }
        if (errMap) {
          //校验未通过
          const msgList = []
          Object.values(errMap).forEach((errList) => {
            errList.forEach((params) => {
              const { rowIndex, column, rules } = params
              rules.forEach((rule) => {
                msgList.push(`第 ${rowIndex + 1} 行 ${column.title} 校验错误：${rule.message}`)
              })
            })
          })
          let msgHtml = ``
          msgList.forEach((msg) => {
            msgHtml += `${msg}<br>`
          })
          // this.$baseMessage(msgHtml, 'warning', '', true)
          console.log(msgHtml)
          return
        }
        let _clickEdit = this.getInfo.extension.clickEdit.value
        if (isEmpty(_clickEdit.method)) {
          console.log('没配置api将不会自动提交')
          return
        }

        console.log('编辑完成事件', column, row, _clickEdit)
        const field = column.property
        const cellValue = row[field]
        // 判断单元格值是否被修改
        if ($table.isUpdateByRow(row, field)) {
          request({
            url: GFCD('dams', 'domain') + this.getInfo.extension.api.value,
            method: 'post',
            data: {
              data: JSON.stringify({
                ...row,
                '#LIMIT#': '1',
                '#PAGE_SIZE#': '50',
              }),
              method: _clickEdit.method,
            },
          }).then(() => {
            if (_clickEdit.tipOpen) {
              this.$baseMessage(`局部保存成功！ ${column.title}=${cellValue}`, 'success')
            }
            $table.reloadRow(row, null, field)
          })
        }
      },
      //反射事件
      emitEvents(result, isDbclick) {
        if (this.getInfo.type.indexOf('uiSelectLayerNew') !== -1) {
          let _value = result || []
          if (!result) {
            if (this.hasCheckboxOrRadio == 'checkbox') {
              _value = this.getTableRef().getCheckboxRecords()
            } else {
              let v = this.getTableRef().getRadioRecord()
              _value = [v]
            }
          }
          this.$emit('outSelected', {
            hasCheckboxOrRadio: this.hasCheckboxOrRadio,
            rows: _value,
            isDbclick,
          })
        }
      },
      //取消选中
      clearSelect() {
        if (this.hasCheckboxOrRadio === 'checkbox') {
          this.getTableRef().clearCheckboxRow()
        } else {
          this.getTableRef().clearRadioRow()
        }
      },
      //按钮操作
      operateClick(v, row) {
        if (v.code.length > 0) {
          //先给选择行打勾
          this.setRadioCheckboxRow({ row: row })
          actionsTask(
            this,
            this.info,
            v.code,
            {
              tableId: this.info._id,
              data: [row],
            },
            () => {
              console.log('操作按钮事件 完成了')
            }
          )
        } else {
          console.log('未配置交互')
        }
      },
      //处理常量
      processConstant(obj = {}) {
        for (let key in obj) {
          obj[key] = processingConstant(this, obj[key])
        }
      },
      //批次属性初始化
      batchAttributeInit() {
        if (!this.getHasPreview) {
          return
        }
        if (this.getInfo.extension.batchAttribute) {
          let batchAttribute = this.getInfo.extension.batchAttribute
          if (isEmpty(batchAttribute.value.api) || isEmpty(batchAttribute.value.method)) {
            console.log('请先配置批次api')
            return
          }
          let _data = { '#LIMIT#': 1, '#PAGE_SIZE#': 100 }
          batchAttribute.value.data.forEach((v) => {
            _data[v.key] = processingConstant(this, v.value)
          })
          console.log('_data', _data)
          //请求
          request({
            url: GFCD('dams', 'domain') + batchAttribute.value.api,
            method: 'post',
            data: {
              data: JSON.stringify(_data),
              method: batchAttribute.value.method,
            },
          }).then((res) => {
            let list = res.data[batchAttribute.value.method].data

            let tableColumns = []
            list.forEach((v) => {
              tableColumns.push({
                _id: `field_${v['#TABLE_KEY#']}`,
                _type: 'field',
                field: v['#TABLE_KEY#'],
                title: v['#TABLE_LABEL#'],
                sortable: true,
                fixed: '',
                width: '150',
                openEdit: false,
                openSearch: false,
                minWidth: '100px',
                showHeaderOverflow: true,
                id: `field_${v['#TABLE_KEY#']}`,
                label: v.title,
                children: [],
                isChecked: false,
                searchConfig: {},
              })
            })
            this.batchAttributeColumns = tableColumns
          })
        }
      },
      //获取自定义请求参数
      $getRequestData() {
        let _data = {}
        if (this.getExtension.requestData && isArray(this.getExtension.requestData.value)) {
          this.getExtension.requestData.value.forEach((item) => {
            let itemVal = item.value
            if (/{[^#{]+}/g.test(item.value)) {
              const dataKey = trim(item.value.substring(2, item.value.length - 1))
              // 如果在formData中查询不到值 则查询数据源缓存值
              itemVal = this.info.data.formData[dataKey] === undefined ? this.dataSourceFormData[dataKey] : this.info.data.formData[dataKey]
            }
            _data[item.key] = processingConstant(this, itemVal)
          })
        }
        return _data
      },
      // 刷新表格
      $refreshTable() {
        this.setFormData(1, this.pageSize)
        // 做数组类型值的拼接
        const params = {}
        for (let key in this.getInfo.data.formData) {
          params[key] = isArray(this.getInfo.data.formData[key]) ? this.getInfo.data.formData[key].join() : this.getInfo.data.formData[key]
        }
        let options = {
          api: this.getInfo.extension.api.value,
          data: params,
          method: this.getInfo.extension.method.value,
        }
        //添加参数(取消选择新组件的数据合格，已在组件自生完成合并)
        // if (this.getInfo.type.indexOf('uiSelectLayerNew') !== -1) {
        //   let requestDataObj = {}
        //   isArray(this.info.extension.requestData.value) &&
        //     this.info.extension.requestData.value.forEach((item) => {
        //       requestDataObj[item.key] = item.value
        //     })
        //   this.processConstant(requestDataObj)
        //   options = {
        //     api: this.info.extension.api.value,
        //     method: this.info.extension.method.value,
        //     getDataKey: this.info.extension.getDataKey.value,
        //     data: merge(this.info.data.formData, requestDataObj),
        //   }
        // }
        //请求
        return this.request(options)
      },
      // 重置表格
      $resetTable() {
        this.setFormData(1, this.pageSize)
        //请求
        return this.request({
          api: this.getInfo.extension.api.value,
          data: this.cacheFormData,
          method: this.getInfo.extension.method.value,
        })
      },
      //获取当前页面
      $getCurrentPage() {
        return this.currentPage
      },
      //获取排序状态
      $getSortType() {
        return this.sortType
      },
      //获取表头
      $getTableColumns() {
        return this.getTableColumns
      },
      $getCheckboxOrRadioVals() {
        let list = cloneDeep(this.getCheckboxOrRadioVals())
        list.forEach((v) => {
          v['#SEQ#'] = this.getTableRef().getRowIndex(v) + 1
        })
        return list
      },
      $getAllData() {
        const _table = this.getTableRef()
        let list = cloneDeep(_table.getData())
        list.forEach((v) => {
          v['#SEQ#'] = _table.getRowIndex(v) + 1
        })
        return list
      },
    },
  })
</script>
<style lang="scss">
  @import './style.scss';
</style>
